package com.example.myapplication.list

import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.example.myapplication.R
import com.example.myapplication.adapter.TestAdapter
import com.hades.common.extend.onBindEvent
import com.hades.common.view.BaseTitleListActivity
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.launch
import org.hades.corelib.base.extend.doLaunch
import org.hades.corelib.base.vm.CoreViewModel

@AndroidEntryPoint
class MyListActivityBase : BaseTitleListActivity() {

    protected val listViewModel: TestListViewModel by viewModels()

    override fun onGetViewModel(): CoreViewModel {
        return listViewModel
    }

    override fun onAdapterCreate(): BaseQuickAdapter<Any, BaseViewHolder> {
        var adapter = TestAdapter(R.layout.test_rv_item) as BaseQuickAdapter<Any, BaseViewHolder>
        adapter
            .also {
                mRecyclerView.layoutManager =
                    LinearLayoutManager(baseContext, RecyclerView.VERTICAL, false)
            }.onBindEvent { adapter, view, position ->
            }
        return adapter
    }

    override fun onCreateViewEvent() {
        launchOnStarted()
    }

    private fun launchOnStarted() {
        doLaunch {
            launch {
                listViewModel.uiFlow.doUICollect {
                    handleData(this.toMutableList())
                }
            }

            launch {
                listViewModel.uiFlow2
                    .drop(1)
                    .collect {
                        // collect 是挂起方法
                        handleData(it.toMutableList())
                    }
            }
        }
    }

    override fun requestData(mPage: Int) {
        // 从viewmodel订阅Stateflow，收集数据，然后调用handleDatas
        listViewModel.requestData(mPage)
    }
}